﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;
using DevExpress.XtraGrid;
using CustomSecurity;

namespace KiemKe
{
    public partial class FrmTheKhoHangKiemKe : BasicForms.FrmSupportPrintableComponents
    {
        public FrmTheKhoHangKiemKe()
        {
            InitializeComponent();
        }
        DsThongKeHangKiemKe dsThongKeKiemKe = new DsThongKeHangKiemKe();

        private void FrmTheKhoHangKiemKe_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedText = "Tùy chọn";

                cmbKho.DataSource = DanhMucKho.Instance.DataView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");

                dsThongKeKiemKe.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Instance.DataTable);    //Lấy tất cả các hàng vì không dùng nhưng có thể đã bán
                gridControlDsVatTuHangHoa.DataSource = dsThongKeKiemKe.VatTuHangHoa;

                chkChooseAllVatTuHangHoa.Checked = false;
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
            }
            catch (Exception ex)
            {
            }

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            if (GeneralLibs.LocalSettings.HeThong.KhoID is Guid)
                cmbKho.EditValue = GeneralLibs.LocalSettings.HeThong.KhoID;
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            string khoCondition = "1=1";
            Guid khoID = Guid.Empty;
            string vatTuHangHoaCondition = "1 = 1";
            if (!chkChooseAllVatTuHangHoa.Checked)
            {
                vatTuHangHoaCondition = "C.VatTuHangHoa1ID IN  (";
                foreach (DataRow row in dsThongKeKiemKe.VatTuHangHoa.Rows)
                {
                    if (row["Choose"] is bool && (bool)row["Choose"])
                    {
                        vatTuHangHoaCondition += string.Format("'{0}', ", row["ID"]);
                    }
                }
                if (vatTuHangHoaCondition.EndsWith("', ")) vatTuHangHoaCondition = vatTuHangHoaCondition.Substring(0, vatTuHangHoaCondition.Length - 2) + ")";
                else vatTuHangHoaCondition = "1 = 0";
            }
            else if (cmbNhomVatTuHangHoa.EditValue != null)
            {
                vatTuHangHoaCondition = "C.VatTuHangHoa1ID IN  (";
                foreach (DataRow row in dsThongKeKiemKe.VatTuHangHoa.Rows)
                {
                    if ((bool)row["Choose"])
                    {
                        vatTuHangHoaCondition += string.Format("'{0}', ", row["ID"]);
                    }
                }
                if (vatTuHangHoaCondition.EndsWith("', ")) vatTuHangHoaCondition = vatTuHangHoaCondition.Substring(0, vatTuHangHoaCondition.Length - 2) + ")";
                else vatTuHangHoaCondition = "1 = 0";
            }

            DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;

            if (cmbKho.EditValue is Guid && (Guid)cmbKho.EditValue != Guid.Empty) khoID = (Guid)cmbKho.EditValue;
            if (khoID != Guid.Empty)
                khoCondition = string.Format("A.Kho1ID = '{0}'", khoID);

            string kyBaoCao = cmbKyBaoCao.Text;
            if (kyBaoCao == "Cả năm") kyBaoCao = "Năm " + GeneralLibs.Config.NamTaiChinh.ToString();
            else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                       ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                       ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

            BasicForms.FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                SqlCommand cmd = con.CreateCommand();
                con.Open();

                cmd.CommandText = string.Format("SELECT D.Ma MaHang, D.Ten TenHang, A.So, D.GiaBia, C.Value8 ChietKhauMua, C.Value1 SoLuongTon, C.Value2 DonGiaVon, C.Value3 ThanhTienVon \n" +
                                                "FROM LoaiChungTu LCT INNER JOIN ChungTu A ON LCT.ID = A.LoaiChungTuID AND LCT.Ma = N'PhieuKiemKe' \n" +
                                                "     INNER JOIN  KhoanMucChungTu C ON A.ChungTuID = C.ChungTuID   \n" +
                                                "     LEFT JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID   \n" +
                                                " WHERE @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi   \n" +
                                                "AND {0}  \n" +
                                                "AND {1}  \n" +
                                                "ORDER BY D.Ten DESC",
                                                khoCondition, vatTuHangHoaCondition);
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                dsThongKeHangKiemKe.TheKiemKe.Clear();
                da.Fill(dsThongKeHangKiemKe.TheKiemKe);

                BasicForms.FrmProgressBar.StartShowProgress();
                int total = dsThongKeHangKiemKe.TheKiemKe.Rows.Count;
                int count = 0;

                gridControl.DataSource = dsThongKeHangKiemKe.TheKiemKe;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
                BasicForms.FrmProgressBar.FinishShowProgress();
            }

            FormatNumberInGridView(gridView);
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            string ngayThongKe = string.Format("Ngày : {0}", System.DateTime.Now);
            PrintWithHeaderAndFooter(true, gridControl, true, true, "Chi tiết hàng đã kiểm kê", "", ngayThongKe, "", "");
        }

        private void cmbNhomVatTuHangHoa_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbNhomVatTuHangHoa.EditValue = Guid.Empty;
        }
        private void cmbNhomVatTuHangHoa_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbNhomVatTuHangHoa.EditValue is Guid && (Guid)cmbNhomVatTuHangHoa.EditValue != Guid.Empty)
                {
                    //Dieu kien loc la ID = cmbNhomVatTuHangHoa.EditValue + ID cac nhom con.
                    string filterNhomCon = "CONVERT('{" + cmbNhomVatTuHangHoa.EditValue.ToString() + "}','System.Guid'), ";
                    DanhMucNhomVatTuHangHoa cacNhomCon = DanhMucNhomVatTuHangHoa.Instance.GetNhomVatTuHangHoaCon((Guid)cmbNhomVatTuHangHoa.EditValue);
                    foreach (NhomVatTuHangHoa nhomCon in cacNhomCon)
                    {
                        filterNhomCon += "CONVERT('{" + nhomCon.ID + "}','System.Guid'), ";
                        //filterNhomCon += string.Format(", '{0}'", nhomCon.ID);
                    }
                    if (filterNhomCon.EndsWith(", ")) filterNhomCon = filterNhomCon.Remove(filterNhomCon.Length - 2);

                    dsThongKeKiemKe.VatTuHangHoa.Clear();
                    string filter = string.Format("NhomVatTuHangHoaID IN ({0}) AND TrangThai = 1 ", filterNhomCon);
                    DataView dt = DanhMucVatTuHangHoa.Filter(filter).DataView;
                    dsThongKeKiemKe.VatTuHangHoa.Merge(dt.ToTable());
                }
                else
                {
                    dsThongKeKiemKe.VatTuHangHoa.Clear();
                    dsThongKeKiemKe.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Instance.DataTable);
                }
                chkChooseAllVatTuHangHoa.Checked = false;
                chkChooseAllVatTuHangHoa.Checked = true;
                FormatNumberInGridView(gridView);
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void chkChooseAllVatTuHangHoa_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                foreach (DataRow row in dsThongKeKiemKe.VatTuHangHoa.Rows)
                {
                    row["Choose"] = chkChooseAllVatTuHangHoa.Checked;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }

        }
    }
}
